import requests
from flask_restful import Resource, fields, marshal_with, reqparse
from flask import request,make_response
from contextlib import closing
import os
from flask_cors import CORS, cross_origin
from utils.util import bytes2human,get_port_params

parser = reqparse.RequestParser()

process_list = {}
# 获取excel文件列表  get请求
class excel_list(Resource):
    def get(self):
        #读取本地地址
        path = "/Users/yyz/Documents/web/python爬虫/static/file/"
        lis = os.listdir(path)
        file_list = []
        for filename in lis:
            dir = path + filename
            size = os.path.getsize(dir)
            ext = dir[dir.rfind('.') + 1:]
            if ext == 'xls' or ext == 'xlsx':
                file_list.append({
                    "etx": ext,
                    "filename": filename,
                    "size": bytes2human(size)
                })
        return {"status": "success", "data": file_list}
class show_process(Resource):
    def get(self):
        uuid = request.args.get("uuid")
        print(3333,process_list,uuid)
        print(34,str(uuid) in process_list)
        if uuid in process_list:
            return {
                "status":"success",
                "data":{
                    "num": process_list[uuid]
                }
            }
        else:
            return {
                "status": "success",
                "data": {
                    "num": 0
                }
            }

# 下载文件接口
class download_excel(Resource):
    def post(selfs):
        try:
            filename = get_port_params("filename")
            uuid = str(get_port_params("uuid"))
            print(48,filename,type(uuid))
            process_list[uuid] = 0
        except:
            return {
                "status": "error",
                "msg": "缺少必要参数"

            }
        # 下载地址
        filepath = "/Users/yyz/Downloads/" + filename
        file_url = "http://127.0.0.1:5000/static/file/" + filename
        return down_excel(uuid,file_url,filepath)
# 下载文件 uuid 唯一值,file_url文件网络地址,file_path文件实际地址
def down_excel(uuid,file_url,file_path):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
    }
    try:
        with closing(requests.get(file_url, headers=headers, stream=True)) as response:
            chunk_size = 5  # 单次请求最大值
            content_size = int(response.headers['content-length'])  # 内容体总大小
            print(content_size)
            data_count = 0
            with open(file_path, "wb") as file:
                # 写入内容
                for data in response.iter_content(chunk_size=chunk_size):
                    file.write(data)
                    data_count = data_count + len(data)
                    process_list[uuid] = int(data_count / content_size * 100)
                    now_jd = (data_count / content_size) * 100
                    print(process_list[uuid])
                    print(now_jd)
                    if process_list[uuid] == 100:
                        print(111)
                        return {
                            "status": "success", "msg": "下载成功"
                        }
    except:
        return {
            "status": "error",
            "msg": "下载失败"

        }